package com.gis3c.online.service.impl;

import com.gis3c.common.exception.BusinessException;
import com.gis3c.online.dao.SurfaceWaterDao;
import com.gis3c.online.entry.SurfaceWaterStation;
import com.gis3c.online.service.SurfaceWaterService;
import com.gis3c.spatial.common.FeatureUtilities;
import com.gis3c.spatial.common.GeometryUtilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hukekuan on 2018/3/22.
 */
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class SurfaceWaterServiceImpl implements SurfaceWaterService {
    @Autowired
    private SurfaceWaterDao surfaceWaterDao;

    @Override
    public String findSurfaceWaterStationListByParams(Map<String,Object> params) {
        String result;
        List<SurfaceWaterStation> resultList = null;
        List<SurfaceWaterStation> stationList
                = surfaceWaterDao.findSurfaceWaterStationListByParams();

        if(params.keySet().size() == 0){
            resultList = stationList;
        }else {
            resultList = new ArrayList<>();
            for(SurfaceWaterStation surfaceWaterStation:stationList){
                if(params.containsKey("stcode") && !params.get("stcode").equals(surfaceWaterStation.getStCode())){
                    continue;
                }
                if(params.containsKey("stationName") && !params.get("stationName").equals(surfaceWaterStation.getStationName())){
                    continue;
                }
                if(params.containsKey("waterLevel") && !params.get("waterLevel").equals(surfaceWaterStation.getLevel())){
                    continue;
                }
                if(params.containsKey("rCode") && !params.get("rCode").equals(surfaceWaterStation.getRiverCode())){
                    continue;
                }
                resultList.add(surfaceWaterStation);
            }
        }
        resultList.forEach(surfaceWaterStation -> surfaceWaterStation.setGeometry(
                GeometryUtilities.CreatePoint(surfaceWaterStation.getLongitude(),surfaceWaterStation.getLatitude())));
        try{
            result = FeatureUtilities.JavaBeans2Json(resultList);
        }catch (IllegalAccessException | IOException e) {
            throw new BusinessException("SurfaceWaterStation实体转GeoJSON出错");
        }
        return result;
    }

    @Override
    public List<SurfaceWaterStation> findSurfaceWaterStations() {
        return surfaceWaterDao.findSurfaceWaterStationListByParams();
    }
}
